'''
Created on 09/03/2011

@author: andrew
'''
from abc import abstractmethod, ABCMeta
from shutil import move
import os
import stat

class MusicFile(object):
    '''
    Interface for abstract classes
    '''
    
    __metaclass__ = ABCMeta
    
    def __init__(self,path):
        '''
        Constructor
        '''
        self.path = path
        self.dir = "/".join(self.path.split('/')[:-1])
        self.name = self.path.split('/')[-1]

    @property
    def writable(self):     
        #Verifica se eh possivel escrever no arquivo
        #TODO: verificar se funciona em Windows
        st = os.stat(self.path)
        if bool(st.st_mode & stat.S_IWUSR) or bool(st.st_mode & stat.S_IWGRP) or bool(st.st_mode & stat.S_IWOTH):
            return True
        else:
            return False

    @property
    def filename(self):
        return self.name

    @filename.setter
    def filename(self,pattern):
        if not(self.writable): raise IOError("Permission denied") 
        replacements = {'%t':self.title,'%a':self.artist,'%b':self.album}
        for old, new in replacements.items():
            pattern = pattern.replace(old, new)
        newpath = self.dir+"/"+pattern
        try:
            os.rename(self.path, newpath)
        except:
            print "Rename error"
        else:
            self.__init__(newpath)

    def delete(self):
        os.remove(self.path)

    def move(self,newdir):
        move(self.path, newdir)
        self.__init__(newdir+"/"+self.name)

    @property
    def info(self):
        return {'filename':self.filename,
                'album':self.album,
                'artist':self.artist,
                'title':self.title}
    @info.setter
    def info(self,dict):
        if not(self.writable): raise IOError("Permission denied") 
        for k, v in dict.items():
            if k != 'filename':
                self.mp3[k] = v
        self.mp3.save()
        if 'filename' in dict:
            self.filename(dict['filename'])

    @abstractmethod
    def album(self):
        pass

    @abstractmethod
    def album(self,album):
        pass

    @abstractmethod
    def artist(self):
        pass

    @abstractmethod
    def artist(self,artist):
        pass

    @abstractmethod
    def title(self):
        pass

    @abstractmethod
    def title(self,title):
        pass

    @abstractmethod
    def sampleRate(self):
        pass

    @abstractmethod
    def bitRate(self):
        pass

    @abstractmethod
    def length(self):
        pass

    @abstractmethod
    def __repr__(self):
        pass
